# pestwatch_lite/api/main.py
from __future__ import annotations
from pathlib import Path
import sys, uuid

# 关键：把“项目根（含 app/ 的那个目录）”加入模块搜索路径
ROOT = Path(__file__).resolve().parents[1]   # .../pestwatch_lite
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))

from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse

# ✅ 正确的绝对导入，而不是 "from app import yolo_demo/geo"
from app.yolo_demo import Detector
from app.geo import read_gps_from_image


OUT = ROOT / "outputs"
OUT.mkdir(parents=True, exist_ok=True)

app = FastAPI(title="PestWatch API", version="0.1.0")
det = Detector()  # 只加载一次模型

@app.get("/healthz")
def healthz():
    return {"ok": True}

@app.post("/detect")
async def detect(file: UploadFile = File(...)):
    data = await file.read()
    tmp = OUT / f"api_{uuid.uuid4().hex}_{file.filename}"
    with tmp.open("wb") as w:
        w.write(data)

    dets = det.predict(tmp)
    lat, lon = read_gps_from_image(tmp)
    return JSONResponse({
        "file": file.filename,
        "gps": {"lat": lat, "lon": lon},
        "detections": dets,
        "count": len(dets)
    })
